<template>
  <div class="app-container">

    <el-card shadow="always" style="margin: 20px">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>


      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="projectMemberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="身份证号" align="center" prop="idCard" width="170"  />
      <el-table-column label="技术职称" align="center" prop="technicalTitleCode" />
      <el-table-column label="职务" align="center" prop="position" />
      <el-table-column label="学位" align="center" prop="degree" />
      <el-table-column label="专业" align="center" prop="major" width="150" />

      <el-table-column label="人员分类" align="center" prop="memberCategoryCode" />
       <el-table-column label="所属课题" align="center" prop="topicName" width="200"/>
      <el-table-column label="是否有工资性收入" align="center" prop="hasSalaryIncome" />
      <el-table-column label="工作单位" align="center" prop="workUnit" width="150"/>

      <el-table-column label="投入本项目的全时工作时间" align="center" prop="workloadManMonth" />
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button

            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button

            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    </el-card>



    <!-- 添加或修改科研项目成员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-card shadow="always" style="margin: 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">

          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="身份证号码" prop="idCard">
            <el-input v-model="form.idCard" placeholder="请输入身份证号码" />
          </el-form-item>

          <el-form-item label="技术职称" prop="technicalTitleCode">
            <el-radio-group v-model="form.technicalTitleCode">
              <el-radio label="正高级">正高级</el-radio>
              <el-radio label="副高级">副高级</el-radio>
              <el-radio label="中级">中级</el-radio>
              <el-radio label="初级">初级</el-radio>
              <el-radio label="其他">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="职务" prop="position">
            <el-input v-model="form.position" placeholder="请输入职务" />
          </el-form-item>

          <el-form-item label="学位" prop="degree">
            <el-radio-group v-model="form.degree">
              <el-radio label="学士">学士</el-radio>
              <el-radio label="硕士">硕士</el-radio>
              <el-radio label="博士">博士</el-radio>
              <el-radio label="其他">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="专业" prop="major">
            <el-input v-model="form.major" placeholder="请输入专业" />
          </el-form-item>

          <el-form-item label="投入工作时间" prop="workloadManMonth">
            <el-input v-model="form.workloadManMonth" placeholder="请输入投入本项目的全时工作时间（人月）" />
          </el-form-item>

          <el-form-item label="人员分类" prop="memberCategoryCode">
            <el-radio-group v-model="form.memberCategoryCode">
              <el-radio label="项目负责人">项目负责人</el-radio>
              <el-radio label="任务负责人">任务负责人</el-radio>
              <el-radio label="项目骨干">项目骨干</el-radio>
              <el-radio label="其他研究人员">其他研究人员</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否有工资性收入" prop="hasSalaryIncome">
            <el-radio-group v-model="form.hasSalaryIncome">
              <el-radio label="Y">是</el-radio>
              <el-radio label="N">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="form.workUnit" placeholder="请输入工作单位" />
          </el-form-item>

          <el-form-item label="承担课题" prop="topicName">
            <el-select v-model="form.topicName" placeholder="请选择课题名称" clearable style="width: 100%">
              <el-option
                v-for="topic in sciProjectTopicList"
                :key="topic.topicName"
                :label="topic.topicName"
                :value="topic.topicName"
              />
            </el-select>
          </el-form-item>

        </el-form>
        </el-card>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>

    </el-dialog>

    <!-- 成员导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="600px" append-to-body>
      <div style="text-align: center;">
        <el-card shadow="always" style="margin: 20px;">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          :data="upload.data"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { listProjectMember, getProjectMember, delProjectMember, addProjectMember, updateProjectMember } from "@/api/sci/projectMember";
import { listPorjectTopic} from "@/api/sci/projectTopic";
import { getToken } from "@/utils/auth";


export default {
  name: "ProjectMember",
  dicts: ['sci_member_role'],
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
    sciProjectTopicList: {
      type: Array,
      default: () => []
    },
    viewFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研项目成员表格数据
      projectMemberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      localIdCounter: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        gender: null,
        idCard: null,
        technicalTitleCode: null,
        position: null,
        degree: null,
        major: null,
        workloadManMonth: null,
        memberCategoryCode: null,
        topicId: null,
        hasSalaryIncome: null,
        workUnit: null,
        projectId: this.projectId,
        topicName: null
      },

      // 表单参数
      form: {
        projectId: this.projectId,
      },

      // 成员导入参数
      upload: {
        // 是否显示弹出层（设备导入）
        open: false,
        // 弹出层标题（设备导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/projectMember/importData",
        data: {
          projectId: null
        }
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const chineseRegex = /^[\u4e00-\u9fa5]+$/;
              if (!chineseRegex.test(value)) {
                callback(new Error('姓名必须为中文汉字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: '身份证号码不能为空', trigger: 'blur' },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '身份证号码格式不正确',
            trigger: 'blur'
          }
        ],
        technicalTitleCode: [
          { required: true, message: "技术职称不能为空", trigger: "blur" }
        ],
        degree: [
          { required: true, message: "学位不能为空", trigger: "blur" }
        ],
        major: [
          { required: true, message: "专业不能为空", trigger: "blur" },
        ],
        workloadManMonth: [
          { required: true, message: "投入本项目的全时工作时间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const numValue = Number(value);
              if (isNaN(numValue) || numValue < 1 || numValue > 120) {
                callback(new Error('请输入1到120之间的有效数值'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        memberCategoryCode: [
          { required: true, message: "人员分类不能为空", trigger: "blur" }
        ],
        hasSalaryIncome: [
          { required: true, message: "是否有工资性收入不能为空", trigger: "blur" }
        ],
        workUnit: [
          { required: true, message: "工作单位不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const chineseRegex = /^[\u4e00-\u9fa5]+$/;
              if (!chineseRegex.test(value)) {
                callback(new Error('工作单位必须为中文汉字'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        topicName: [
          { required: true, message: "承担课题不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    if(this.projectId !== null){
      this.getList();
    }else{
      this.loading=false;
    }
  },
  watch: {
    projectId(newVal) {
      // 当 projectId 变化时，更新查询参数并重新获取列表
      if (newVal === null) {
        this.queryParams.projectId = null;
        this.projectMemberList = [];
        this.total = 0;
        return;
      }
      this.queryParams.projectId = newVal;
      this.getList();
    }
  },
  methods: {
    /** 查询科研项目成员列表 */
    getList() {
      this.loading = true;
      listProjectMember(this.queryParams).then(response => {
        this.projectMemberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: this.projectId,
        userId: null,
        nickName: null,
        role: null,
        topicId: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        id: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.editFlag = false;
      this.title = "添加科研项目成员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProjectMember(id).then(response => {
        this.editFlag = true;
        this.form = response.data;
        this.open = true;
        this.title = "修改科研项目成员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProjectMember(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProjectMember(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除科研项目成员编号为"' + ids + '"的数据项？').then(function() {
        return delProjectMember(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/projectMember/export', {
        ...this.queryParams
      }, `projectMember_${new Date().getTime()}.xlsx`)
    },
    getTopicName(topicId) {
      if (!topicId) return '无';
      const topic = this.sciProjectTopicList.find(t => t.id === topicId);
      return topic ? topic.topicName : '未知课题';
    },
    getTopicList() {
      const query = {
        projectId: this.projectId
      }
      listPorjectTopic(query).then(response => {
        this.sciProjectTopicList = response.rows;
      });
    },



      /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "项目成员";
      this.upload.open = true;
      this.upload.data.projectId = this.projectId;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/projectMember/importTemplate', {
      }, `项目成员模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.upload.open=false;
    }

  }
};
</script>
